package com.itheima.controller;

import com.itheima.anno.OperationLog;
import com.itheima.domain.Result;
import com.itheima.domain.pojo.Dept;
import com.itheima.service.DeptService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@RequestMapping("depts")
@RestController
@Slf4j
public class DeptController {
    @Autowired
    private DeptService deptService;

// 方式一：    @RequestMapping(value = "/depts",method = RequestMethod.GET) 通过method属性指定请求方式
    @GetMapping// 方式二：通过@GetMapping注解指定请求方式，还有@PostMapping，@PutMapping，@DeleteMapping
    public Result list() {
        List<Dept> deptList= deptService.list();
        return Result.success(deptList);
    }
/*根据ID删除部门 - 简单参数接收: 方式一 (HttpServletRequest)*/
//    @DeleteMapping("/depts")
//    public Result delete(HttpServletRequest request){
//        String id = request.getParameter("id");
//        int id1=Integer.parseInt(id);
//        System.out.println("根据ID删除部门，"+id1
//     return null;
//        );
//
//    }

/*通过@RequestParam注解接受参数，注意事项：一旦使用@RequestParam注解，那么参数一定要传递，否则报错，如果不想传参，可以设置required属性为false*/
//    @DeleteMapping("/depts")
//    public Result delete(@RequestParam Integer deptId){
//
//        System.out.println("根据ID删除部门，"+deptId);
//        return null;
//
//}
@DeleteMapping
@OperationLog
public Result delete(@RequestParam Integer id)  {
//1.接受参数
//    System.out.println("接受参数，"+id);
    log.info("接受参数，"+id);
    //2.调用service层
    deptService.deleteById(id);
    //3.响应数据给前端
    return Result.success();
}


@PostMapping
@OperationLog
    public Result add(@RequestBody Dept dept){
//    System.out.println("添加部门，"+dept);
    log.info("添加部门，"+dept);
    deptService.add(dept);
    return Result.success();
}

@GetMapping("/{id}")
//@PathVariable注解：接收路径参数
    public Result getInfo(@PathVariable Integer id){
//    System.out.println("根据ID查找部门，"+id);
    log.info("根据ID查找部门，"+id);
    Dept dept= deptService.getInfo(id);
    return Result.success(dept);
}

@PutMapping
@OperationLog("修改部门")
    public Result update(@RequestBody Dept dept){
//    System.out.println("修改部门，"+dept);
    log.info("修改部门，"+dept);
    deptService.updateById(dept);
    return Result.success();
}

}
